package com.roadjava.demo10.advice;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class RoadJavaControllerAdvice10 {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public String handleEx(BindException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError fe : fieldErrors) {
            sb.append("属性：").append(fe.getField())
                    .append("校验不通过，原因：").append(fe.getDefaultMessage())
                    .append("；");
        }
        return sb.toString();
    }
}
